package org.alesv.entranceExams.dao.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

import org.alesv.entranceExams.Config;
import org.alesv.entranceExams.dao.LoginDao;
import org.alesv.entranceExams.model.UserProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;


/**
 * 
 * @author asantamaria
 */
@Repository
public class LoginDaoImpl implements LoginDao {

	/**
	 * Acceso al fichero de configuración de la aplicación.
	 */
	@Autowired
	private Config config;

	/**
	 * Usado para escribir trazas.
	 */
	private final Logger log = LoggerFactory.getLogger(LoginDaoImpl.class);

	private Map<String, UserProfile> users = null;

	@Override
	public UserProfile logIn(String user, String password) {
		log.debug("Trying to log in");

		UserProfile result = null;

		if (users == null) {

			users = new HashMap<String, UserProfile>();

			try {

				StringTokenizer usersTz = new StringTokenizer(config.getUsers());
				StringTokenizer passwordsTz = new StringTokenizer(
						config.getPasswords());
				StringTokenizer userNamesTz = new StringTokenizer(
						config.getUserNames());

				while (usersTz.hasMoreTokens()) {
					UserProfile userProfile = new UserProfile();
					userProfile.setUser(usersTz.nextToken());
					userProfile.setPassword(passwordsTz.nextToken());
					userProfile.setUserName(userNamesTz.nextToken());
					users.put(userProfile.getUser(), userProfile);
				}

			} catch (Exception e) {
				log.error(
						"There were a problem trying to get users data to log in",
						e);
			}

		}

		UserProfile candidateUserProfile = users.get(user);
		if (candidateUserProfile != null
				&& candidateUserProfile.getPassword() != null
				&& candidateUserProfile.getPassword().equals(password)) {
			result = candidateUserProfile;
		}

		return result;
	}

	@Override
	public boolean logOut(String user) {
		log.debug("Trying to log out");

		// There is nothin go do here in this implementation of the DAO

		return true;
	}
}
